package com.weight.common.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.weight.common.enums.ResultEnum;
import com.weight.common.exception.CSException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CommonUtils {
	/**
	 * 产生32位随机字符串id
	 * @return
	 */
	public static String getUUId() {
		return UUID.randomUUID().toString().replace("-", "");
	}
	/**
	 * 获取所有  校验出错信息提示
	 * @param bindingResult
	 * @return
	 */
	public static String getErrorMsg(BindingResult bindingResult) {
		StringBuilder sb=new StringBuilder();
		int kk=0;
		for(ObjectError objectError : bindingResult.getAllErrors()){  
	//        sb.append(((FieldError)objectError).getField() +" : ").append(objectError.getDefaultMessage());  
			if(kk>0) {
				sb.append(";<br/>");
			}
			sb.append(objectError.getDefaultMessage());  
			kk++;
	    } 
//		 bindingResult.getFieldError().getDefaultMessage();
		return sb.toString();
	}
	/**
	 *  校验出错信息
	 * @param bindingResult
	 * @param obj
	 */
	public static void validateBindingResult(BindingResult bindingResult,Object obj) {
		if(bindingResult.hasErrors()) {
			String errorMsg=CommonUtils.getErrorMsg(bindingResult);
			log.error("保存参数不正确，Object={},message={}", obj,errorMsg);
			throw new CSException(ResultEnum.ILLEGAL_DATA_SUBMIT,errorMsg);
		}
	}
	/**
	  * List是否相同存在
	  * @param idList
	  * @param objList
	  */
	public static void validateExistList(List idList,List objList) {
		if(idList.size()!=objList.size()) {
			idList =(List) CollectionUtils.subtract(objList, idList);
			log.error("数据已删除或不存在：idList={}",idList);
			throw new CSException(ResultEnum.NOT_FOUND,"批量删除ID不存在,id："+idList);
		}
	}
	/**
	 * 对象是否存在
	 * @param obj
	 * @param map
	 */
	public static void validateExistObj(Object obj,Map map) {
		if(obj == null){
			log.error(ResultEnum.NOT_FOUND_OBJECT.getMessage()+"：map={}",map);
			throw new CSException(ResultEnum.NOT_FOUND_OBJECT);
		}
	}
	/**
	 * ID是否存在，详情，删除
	 * @param obj
	 * @param map
	 */
	public static void validateExistID(String id) {
		if(StringUtils.isBlank(id)) {
			log.error(ResultEnum.ILLEGAL_ID_SUBMIT.getMessage());
			throw new CSException(ResultEnum.ILLEGAL_ID_SUBMIT);
		}
	}
	/**
	 * 校验List是否存在。批量删除ID
	 * @param idList
	 */
	public static void validateExistIDList(List idList) {
		log.info("idList={}",idList);
		if(idList==null||idList.size()==0) {
//			log.error("删除菜单信息表操作--批量删除入参,id为空");
//			throw new CSException(ResultEnum.NOT_FOUND,"批量删除操作,id为空");
			log.error(ResultEnum.ILLEGAL_ID_SUBMIT.getMessage());
			throw new CSException(ResultEnum.ILLEGAL_ID_SUBMIT);
		}
	}
	/**
     * 	 接收指令转换
     * @param commandType 类型
     * @param command 指令
     * @param message 指令内容
     * @return
     */
    public static String operSaveMSG(String commandType, String command,String message){
    	System.out.println("operSaveMSG1111");
		System.out.println(commandType);
		System.out.println(command);
		System.out.println(message);
		//多条指令合并 存储第一条
		if(StringUtils.indexOf(message, "A55A") > 0) {
			message = message.substring(0,StringUtils.indexOf(message, "A55A"));
		}
    	if(StringUtils.isBlank(commandType) 
    			|| StringUtils.equals("0220", command) 
    			|| StringUtils.equals("0204", command)
    			|| StringUtils.equals("0100", command)) {
			commandType = "3";
		}
    	//01 00：变量地址  00为正，01时为负   12 34 56：数据内容
    	if(StringUtils.equals("0100", command) && StringUtils.length(message) < 21) {
			 String mthType = message.substring(0,2);
			 if(StringUtils.equals("00", mthType)) {
				 message = message.substring(2);
			 }else if(StringUtils.equals("01", mthType)) {
				 message = "-" + message.substring(2);
			 }
		}
    	
		switch(commandType){
		    case "1" :
		       //十六进制
		    	message = CommonUtils.hextToString(message); 
		       break;  
		    case "2" :
		       //ASCII码
		    	message = CommonUtils.asciiToStringHex(message);
		       break;  
		    case "3":
			       //十进制
			    break;  		   
		    default : //十进制
		}
		
		System.out.println("operSaveMSG222"); 
		System.out.println(message);
		
		return message;
    }
	
	/**
	 * 	发送指令 转换
	 * @param commandMesg
	 * @param sendMsg
	 * @param commandType
	 * @return
	 */
	public static String operSendMsg(String commandMesg, String sendMsg, Integer commandType) {
		 commandType = commandType == null ?4:commandType;
		 if(StringUtils.startsWith(commandMesg, "04")) {
			 commandType = 16;
		 }
		 log.info("sendMsg={}",sendMsg);
		 System.out.println("发送1：");
		 System.out.println(sendMsg);
		 
		
		 
		 switch(commandType){
		    case 1 :
		       //十六进制
		    	sendMsg = CommonUtils.strToHexString(sendMsg);		    
		       break;  
		    case 2 :
		       //ASCII码
		    	sendMsg = CommonUtils.stringToAsciigHex(sendMsg);
		       break;  
		    case 3 :
			       //十进制
			    break;  
		    case 16 :
			       //十进制
		    	sendMsg = CommonUtils.toHexString(sendMsg);
			    break;
			    
		    default : //十进制
		      
		}
		 
		 System.out.println("发送2：");
		 System.out.println(sendMsg);
		 //补0
		 sendMsg = checkSenfMessage(sendMsg);
		 //指令拼装
		 sendMsg = "A55A" + String.format("%02d", sendMsg.length()/2 +2) + commandMesg + sendMsg;
		 
		 System.out.println("发送3：");
		 System.out.println(sendMsg);
		 
		 return sendMsg;
	}
	

	/**
	 * 	长度补0
	 * @param sendMsg
	 * @return
	 */
	public static String checkSenfMessage(String value) {
		if(value.length()%2>0) value = "0" + value;
		
		return value;
	}
	
	/**
	 * 	10 转16
	 * @param str
	 * @return
	 */
	public static String toHexString(String str) {
		int valueTen = Integer.parseInt(str);
		String strHex = Integer.toHexString(valueTen); 
		return strHex.toUpperCase();
	}
	/**
	 *  16 转10 
	 * @param value
	 * @return
	 */
	public static String hextToString(String value){
		
		return ""+Integer.parseInt(value,16);
	}
	/**
	 *  10串转16 串
	 * @param value
	 * @return
	 */
	public static String strToHexString(String value)  
	{  
	    StringBuffer sbu = new StringBuffer();  
	    value = checkSenfMessage(value);
	    for (int i = 0; i < value.length(); i = i+2) {  
	        sbu.append(toHexString(value.substring(i,i+2)));  
	    }  
	    return sbu.toString();  
	} 
	/**
	 * 16串转10串
	 */
	public static String hexToStrString(String value)  
	{  
	    StringBuffer sbu = new StringBuffer();  
	    value = checkSenfMessage(value);
	    for (int i = 0; i < value.length(); i = i+2) {  
	        sbu.append(hextToString(value.substring(i,i+2)));  
	    }

	    return sbu.toString();  
	}  
	/**
	 * 	字符串的  转成ASCII 
	 */
	public static String stringToAscii(String value)  
	{  
	    StringBuffer sbu = new StringBuffer();  
	    
	    for (int i = 0; i < value.length(); i++) {  
	        sbu.append((int) value.charAt(i));  
	    }

	    return sbu.toString();  
	} 
	
	/**
	 * 	字符串的  转成ASCII 16
	 */
	public static String stringToAsciigHex(String value)  
	{  
		StringBuffer sbu = new StringBuffer();  
	    
	    for (int i = 0; i < value.length(); i++) {  
	        sbu.append((int) value.charAt(i));  
	    }

	    return strToHexString(sbu.toString());  
	} 
	
	
	/**
	 * ASCII	  转成   字符串 
	 */
	public static String asciiToString(String value)  
	{  
	    StringBuffer sbu = new StringBuffer();  
	    value = checkSenfMessage(value);
	    for (int i = 0; i < value.length() -2 ; i = i+2) {  
	        sbu.append((char) Integer.parseInt(value.substring(i,i+2)));  
	    }

	    return sbu.toString();  
	} 
	/**
	 * ASCII	  转成   字符串  16
	 */
	public static String asciiToStringHex(String value)  
	{  
		value = hexToStrString(value);
	    StringBuffer sbu = new StringBuffer();  
	    value = checkSenfMessage(value);
	    for (int i = 0; i < value.length() ; i = i+2) {  
	        sbu.append((char) Integer.parseInt(value.substring(i,i+2)));  
	    }
	    return sbu.toString();  
	}
	
	/**
	 * 16进制转换成为string类型字符串
	 * @param s
	 * @return
	 */
	public static String hexStringToString(String s) {
	 if (s == null || s.equals("")) {
	  return null;
	 }
	 s = s.replace(" ", "");
	 byte[] baKeyword = new byte[s.length() / 2];
	 for (int i = 0; i < baKeyword.length; i++) {
	  try {
	   baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
	  } catch (Exception e) {
	   e.printStackTrace();
	  }
	 }
	 try {
	  s = new String(baKeyword, "UTF-8");
	  new String();
	 } catch (Exception e1) {
	  e1.printStackTrace();
	 }
	 return s;
	}
	
	 
}
